import { useState, useRef } from 'react'
import { Upload, Button, message, Spin } from 'antd'
import { InboxOutlined, UploadOutlined } from '@ant-design/icons'
import * as XLSX from 'xlsx'

const { Dragger } = Upload

const ExcelImport = ({ onImportData, loading }) => {
  const [uploading, setUploading] = useState(false)
  const fileInputRef = useRef(null)

  // 处理文件上传
  const handleFileUpload = (file) => {
    if (!file) return false

    const fileType = file.type
    const fileName = file.name
    const isExcel =
      fileType ===
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
      fileType === 'application/vnd.ms-excel' ||
      fileName.endsWith('.xlsx') ||
      fileName.endsWith('.xls')

    if (!isExcel) {
      message.error('只支持Excel文件格式 (.xlsx, .xls)')
      return false
    }

    setUploading(true)

    const reader = new FileReader()
    reader.onload = (e) => {
      try {
        const data = new Uint8Array(e.target.result)
        const workbook = XLSX.read(data, { type: 'array' })

        // 获取第一个工作表
        const firstSheetName = workbook.SheetNames[0]
        const worksheet = workbook.Sheets[firstSheetName]

        // 转换为JSON格式
        const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 })

        // 过滤空行
        const filteredData = jsonData.filter(
          (row) =>
            row &&
            row.length > 0 &&
            row.some(
              (cell) => cell !== null && cell !== undefined && cell !== ''
            )
        )

        if (filteredData.length === 0) {
          message.error('Excel文件中没有找到有效数据')
          setUploading(false)
          return
        }

        // 如果第一行是表头，跳过它
        const hasHeader =
          filteredData[0] &&
          filteredData[0].some(
            (cell) =>
              typeof cell === 'string' &&
              (cell.includes('编号') ||
                cell.includes('日期') ||
                cell.includes('工作内容') ||
                cell.includes('耗时') ||
                cell.includes('项目'))
          )

        const dataToImport = hasHeader ? filteredData.slice(1) : filteredData

        if (dataToImport.length === 0) {
          message.error('Excel文件中没有找到有效的数据行')
          setUploading(false)
          return
        }

        message.success(`成功读取 ${dataToImport.length} 条记录`)
        onImportData(dataToImport)
      } catch (error) {
        console.error('文件解析错误:', error)
        message.error('文件解析失败，请检查文件格式')
      } finally {
        setUploading(false)
      }
    }

    reader.onerror = () => {
      message.error('文件读取失败')
      setUploading(false)
    }

    reader.readAsArrayBuffer(file)
    return false // 阻止自动上传
  }

  // 拖拽上传配置
  const uploadProps = {
    name: 'file',
    multiple: false,
    beforeUpload: handleFileUpload,
    showUploadList: false,
    disabled: uploading || loading,
  }

  // 处理点击上传
  const handleClickUpload = () => {
    fileInputRef.current?.click()
  }

  return (
    <Spin spinning={uploading || loading} tip='正在处理文件...' size='large'>
      <div>
        <Dragger {...uploadProps}>
          <p className='ant-upload-drag-icon'>
            <InboxOutlined />
          </p>
          <p className='ant-upload-text'>点击或拖拽文件到此区域上传</p>
          <p className='ant-upload-hint'>
            支持Excel文件格式 (.xlsx, .xls)
            <br />
            数据格式：编号 | 日期 | 工作内容 | 耗时 | 剩余 | 对象 | 产品 | 执行
            | 项目
          </p>
        </Dragger>

        <div style={{ marginTop: '16px', textAlign: 'center' }}>
          <Button
            type='primary'
            icon={<UploadOutlined />}
            onClick={handleClickUpload}
            loading={uploading || loading}
            disabled={uploading || loading}
          >
            选择文件上传
          </Button>
          <input
            ref={fileInputRef}
            type='file'
            accept='.xlsx,.xls'
            style={{ display: 'none' }}
            onChange={(e) => {
              const file = e.target.files[0]
              if (file) {
                handleFileUpload(file)
              }
            }}
          />
        </div>

        <div
          style={{
            marginTop: '16px',
            padding: '12px',
            backgroundColor: '#f9f9f9',
            borderRadius: '4px',
          }}
        >
          <h4 style={{ marginBottom: '8px', color: '#666' }}>使用说明：</h4>
          <ul
            style={{
              margin: 0,
              paddingLeft: '20px',
              fontSize: '14px',
              color: '#666',
            }}
          >
            <li>支持 .xlsx 和 .xls 格式的Excel文件</li>
            <li>
              数据应包含：编号、日期、工作内容、耗时、剩余、对象、产品、执行、项目
            </li>
            <li>日期格式支持：YYYY-MM-DD、YYYY/MM/DD 等常见格式</li>
            <li>系统会自动识别表头行并跳过</li>
            <li>空行会被自动过滤</li>
          </ul>
        </div>

        <div
          style={{
            marginTop: '16px',
            padding: '12px',
            backgroundColor: '#f9f9f9',
            borderRadius: '4px',
          }}
        >
          <h4 style={{ marginBottom: '8px', color: '#666' }}>工时范围：</h4>
          <ul
            style={{
              margin: 0,
              paddingLeft: '20px',
              fontSize: '14px',
              color: '#666',
            }}
          >
            <li>上月25-本月24</li>
          </ul>
        </div>
      </div>
    </Spin>
  )
}

export default ExcelImport
